package cn.bitkit.tools.file;

import cn.bitkit.base.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @author changbo
 *
 */
@Slf4j
public class ConfigHelper {

	private static final ThreadLocal<String> CONFIG_FILE = new ThreadLocal<>();
	private static final Map<String, Map<String, String>> CONFIG = new ConcurrentHashMap<>();
	private static final String DEFAULT_FILE = "application.properties";

	private static void initDefault(){
		if (CONFIG_FILE.get() == null){
			CONFIG_FILE.set("application.properties");
		}
	}

	public synchronized static void initConfig(String fileName){
		if(CONFIG.get(fileName) == null){
			Map<String, String> data = ConfigUtil.readConfig(fileName);
			if(DEFAULT_FILE.equals(fileName)){
				String active = data.get("spring.profiles.active");
				if(active != null) {
					String activeFile = "application-" + active + "." + FileUtil.getSuffix(fileName);
					Map<String, String> dataActive = ConfigUtil.readConfig(activeFile);
					data.putAll(dataActive);
				}
			}
			CONFIG.put(fileName, data);
		}
	}

	public static void setConfigFile(String configFile){
		ConfigHelper.CONFIG_FILE.set(configFile);
	}

	public static String getValue(String key){
		initDefault();
		String file = CONFIG_FILE.get();
		Map<String, String> map = CONFIG.get(file);
		if(map == null){
			initConfig(file);
			map = CONFIG.get(file);
		}
		return map.get(key);
	}

	public static boolean getBoolean(String key){
		return StringUtil.toBoolean(StringUtil.getValue(getValue(key)));
	}

	public static int getInt(String key){
		return StringUtil.toInt(StringUtil.getValue(getValue(key)));
	}

	public static long getLong(String key){
		return StringUtil.toLong(StringUtil.getValue(getValue(key)));
	}

}
